<?php 

define("FETCH_MODE_NONE", -1);
define("FETCH_MODE_CELL",0);
define("FETCH_MODE_ROW",1);
define("FETCH_MODE_COLUMN",2);
define("FETCH_MODE_TABLE",3);
define("DEFAULT_LANGUAGE",'vn');
define("DEFAULT_PAGE",'homepage');
define("HEIGHT",'523px');
define("WIDTH",'750px');
define("HIDE_DEMO_SECOND",'250');
define("HIDE_CHECK_TIME",'40');
define("KEYWORDS",'công ty IADE,kiến trúc,xây dựng,thiết kế,trang trí,nội thất,công trình,dự án,architecture,design,construction,project,funiture');

global $page;
global $action;
global $language;
global $login;
global $pages;

class Db
{
	private static $_link;
	
	static function mysql_query($query,$fetch_mode=2)
	{
		Db::mysql_connect();
		$result = mysql_query($query);
		if (!$result) 
		{
			die('Invalid query: ' . mysql_error());
		}
		switch($fetch_mode)
		{
			case FETCH_MODE_CELL:
				if($row=mysql_fetch_row($result))
					return $row[0];						
				break;
			case FETCH_MODE_TABLE:
				$table=array();
				while($row=mysql_fetch_assoc($result))
					$table[]=$row;
				return $table;
				break;
			case FETCH_MODE_COLUMN:
				$array=array();
				while($row=mysql_fetch_row($result))
					$array[]=$row[0];
				return $array;
				break;
			case FETCH_MODE_NONE:
				return true;
				break;
		}
		return null;
	}
	
	static function mysql_connect()
	{
		if(Db::$_link==null)
		{
			$link = mysql_connect(SVR, USN, PWD);
			if (!$link) 
			{
				die('Could not connect: ' . mysql_error());
			}
			$db_selected = mysql_select_db(DTB, $link);
			if (!$db_selected) 
			{
				die ('Can\'t use foo : ' . mysql_error());
			}
			mysql_set_charset('utf8',$link); 
			Db::$_link=$link;
		}
	}
	
	static function mysql_close()
	{
		mysql_close(Db::$_link);
	}
}

class Album
{
	//engine1 {effect: fade, delay: 6s, duration: 2s, image: 750x532, template: block}
	//engine2 {effect: basic linear}
	static public function fetch_album_content($path,$engine)
	{
		$iterator = new DirectoryIterator($path);
		$filenames=array();
		foreach ($iterator as $fileinfo) 
		{
			if ($fileinfo->isFile()) 
			{
				$filename=$fileinfo->getFilename();
				$filenames[]=$filename; 
			}
		}				
		sort($filenames,SORT_NUMERIC );
		$ws_images='';
		$ws_bullets='';
		$i=0;
		foreach ($filenames as $filename) 
		{
			$src=BASE_URL.$path.'/'.$filename;
			$title='';
			$ws_images.='
			<li>
				<img src="'.$src.'" alt="'.$title.'" title="'.$title.'" id="wows'.$i.'" />
			</li>';
			//$tooltip_src=str_replace('/images/','/_thumbs/images/',$src);
			$ws_bullets.='<a href="#" title="'.$title.'">';
			//$ws_bullets.='<img src="'.$tooltip_src.'" alt="'.$title.'" />';
			//$ws_bullets.=($i+1);
			$ws_bullets.='</a>';
			$i++;
		}					
		?>
								
		<link rel="stylesheet" type="text/css" href="<?php echo BASE_URL?>ext/js/slider/<?=$engine?>/style.css" />

		<div id="wowslider-container1">
			<div class="ws_images">
				<ul>
					<?php echo $ws_images;?>
				</ul>
			</div>
			<div class="ws_bullets">
				<div>
					<?php echo $ws_bullets;?>
				</div>
			</div>
			<!--<a class="wsl" href="#">HTML Photo Gallery Generator by WOWSlider.com v2.1.3</a>-->
		</div>
		<script type="text/javascript" src="<?php echo BASE_URL?>ext/js/slider/<?=$engine?>/wowslider.js"></script>
		<script type="text/javascript" src="<?php echo BASE_URL?>ext/js/slider/<?=$engine?>/script.js"></script>
		<script>
			$(function(){
				setTimeout("hideDemo(0)",'<?php echo HIDE_DEMO_SECOND;?>');
			});
			
			function hideDemo(i)
			{
				if($('.ws_images div').length>0)
				{
					$('.ws_images div').css('display','none');
				}
				else 
				{
					if(i<<?php echo HIDE_CHECK_TIME?>)
						setTimeout("hideDemo("+(i+1)+")",'<?php echo HIDE_DEMO_SECOND;?>');
				}
			}
		</script>
	<?php
	}

	static public function view()
	{
		switch(Album::$_page_name)
		{
			case 'homepage':
				$path="userfiles/images/homepage";
				Album::fetch_album_content($path,'engine1');
				break;
			case 'image':
				$project=isset($_GET['project'])?$_GET['project']:'';
				$year=isset($_GET['year'])?$_GET['year']:'';
				$type=isset($_GET['type'])?$_GET['type']:'selected-projects';
				$path="userfiles/images/project/$type/$year/$project";
				Album::fetch_album_content($path,'engine2');
				break;
			case 'project':
				$type=isset($_GET['type'])?$_GET['type']:'selected-projects';
				$project=isset($_GET['project'])?$_GET['project']:'';
				$year=isset($_GET['year'])?$_GET['year']:'';
				$path="userfiles/images/project".($type==''?'':"/$type").($year==''?'':"/$year");
				$iterator = new DirectoryIterator($path);
				$filenames=array();
				foreach ($iterator as $fileinfo) 
				{
					if ($fileinfo->isDir() && $fileinfo->getFilename()!='.' && $fileinfo->getFilename()!='..') 
					{
						$filename=$fileinfo->getFilename();
						$filenames[]=$filename; 
					}
				}				
				if(count($filenames)==0)
				{
					echo '<h1>'.LUPDATING.'</h1>';
					break;
				}
				sort($filenames,SORT_NUMERIC );
				$filenames=array_reverse($filenames);
				$i=0;
				?>
				<ul id='list-project'>
				<?php
				foreach($filenames as $filename)
				{
					$src=BASE_URL.$path.'/'.$filename.'/project.jpg';
					if(!file_exists(str_replace(BASE_URL,'',$src)))
						$src=BASE_URL.$path.'/'.$filename.'/project.JPG';
					$tooltip_src=str_replace('/images/','/_thumbs/images/',$src);
					$encode_filename=urlencode($filename);
					if($type=='selected-projects')
						$link="?page=image&project=$encode_filename";
					else
						$link=($year==''?"?page=project&year=$encode_filename":"?page=image&year=$year&project=$encode_filename");
					$link.="&type=$type";
					$title=$filename;
					?>
					<li class='listingthumb<?php echo ($i++)%3==1?" middle-column":"";?>'>
						<a href='<?php echo $link;?>' >
							<img src="<?php echo $tooltip_src?>"  />
						</a>
						<span class='listingthumb-caption'>
							<a href='<?php echo $link;?>' >
								<?php echo $title?>
							</a>
						</span>
					</li>
					<?php
				}
				?>
				</ul>
				<?php
				break;
		}
	}
	
	static public function edit()
	{
	?>
	<script type="text/javascript" src="<?php echo BASE_URL?>ext/js/ckfinder/ckfinder.js"></script>
	<p id='finder'>
		<script type="text/javascript">

			// This is a sample function which is called when a file is selected in CKFinder.
			function showFileInfo( fileUrl, data )
			{
				var msg = 'The selected URL is: <a href="' + fileUrl + '">' + fileUrl + '</a><br /><br />';
				// Display additional information available in the "data" object.
				// For example, the size of a file (in KB) is available in the data["fileSize"] variable.
				if ( fileUrl != data['fileUrl'] )
					msg += '<b>File url:</b> ' + data['fileUrl'] + '<br />';
				msg += '<b>File size:</b> ' + data['fileSize'] + 'KB<br />';
				msg += '<b>Last modifed:</b> ' + data['fileDate'];

				// this = CKFinderAPI object
				this.openMsgDialog( "Selected file", msg );
			}

			// You can use the "CKFinder" class to render CKFinder in a page:
			var finder = new CKFinder();
			// The path for the installation of CKFinder (default = "/ckfinder/").
			finder.basePath = '../../';
			// This is a sample function which is called when a file is selected in CKFinder.
			finder.selectActionFunction = showFileInfo;
			finder.height = '<?php echo HEIGHT?>';
			finder.width  = '<?php echo WIDTH?>';
			finder.create();

			// It can also be done in a single line, calling the "static"
			// create( basePath, width, height, selectActionFunction ) function:
			// CKFinder.create( '../../', null, null, showFileInfo );

			// The "create" function can also accept an object as the only argument.
			// CKFinder.create( { basePath : '../../', selectActionFunction : showFileInfo } );
			
			$(function(){
				setTimeout("hideFooterDemo(0)",'<?php echo HIDE_DEMO_SECOND;?>');
				setTimeout("hideCenterDemo(0)",'<?php echo HIDE_DEMO_SECOND;?>');
			});
			
			function hideFooterDemo(i)
			{
				if(window.frames[0] && $('#sidebar_wrapper div.tool_panel',window.frames[0].document).length>0)
				{
					$('#sidebar_wrapper div.tool_panel',window.frames[0].document).css('display','none');
					$('#folders_view',window.frames[0].document).css('height','100%');
				}
				else 
				{
					if(i<<?php echo HIDE_CHECK_TIME?>)
						setTimeout("hideFooterDemo("+(i+1)+")",'<?php echo HIDE_DEMO_SECOND;?>');
				}
			}
			
			function hideCenterDemo(i)
			{
				if(window.frames[0] && $('h4.message_content',window.frames[0].document).length>0)
				{
					$('h4.message_content',window.frames[0].document).css('display','none');
				}
				else 
				{
					if(i<<?php echo HIDE_CHECK_TIME?>)
						setTimeout("hideCenterDemo("+(i+1)+")",'<?php echo HIDE_DEMO_SECOND;?>');
				}
			}
		</script>
	</p>
	<?php
	}
	
	static private $_page_name;
	static public function init($page_name)
	{
		global $action;
		Album::$_page_name=$page_name;
		switch($action)
		{
			case '':
				Album::view();
				break;
			case 'edit':
				Album::edit();
				break;
		}
	}
}

class Page
{
	static public function fetch_page_content()
	{
		global $language;
		$column='page_content_'.$language;
		$query="SELECT $column FROM tbl_page WHERE page_name='".Page::$_page_name."'";
		$page_content=Db::mysql_query($query,FETCH_MODE_CELL);
		return $page_content;
	}
	
	static public function view()
	{
		$page_content=Page::fetch_page_content();
		echo $page_content;
	}
	
	static public function edit()
	{
		global $language;
		if(isset($_POST['submit_value']))
		{
			if($_POST['submit_value']=='Save')
			{
				$page_content=$_POST['page_content'];
				$page_content=stripslashes($page_content);
				$query="UPDATE tbl_page SET page_content_$language='$page_content' WHERE page_name='".Page::$_page_name."'";
				Db::mysql_query($query,FETCH_MODE_NONE);
			}
			else if($_POST['submit_value']=='Reset to default')
			{
				$page_content=Db::mysql_query("SELECT page_default_content_$language FROM tbl_page WHERE page_name='".Page::$_page_name."'",FETCH_MODE_CELL);
			}
		}
		else
			$page_content=Page::fetch_page_content();		
		$height=HEIGHT-133;
		$width=WIDTH-3;
	?>
		<script type="text/javascript" src="<?php echo BASE_URL?>ext/js/ckeditor/ckeditor.js" ></script>
		<script>
			$(document).ready(function(){
				var ckfinder_url='<? echo BASE_URL?>ext/js/ckfinder/';				
				CKEDITOR.replace($("#editor")[0], { 
				height:'<?php echo $height;?>'
				, width:'<?php echo $width;?>'
				,toolbar:'Full'					
				,filebrowserBrowseUrl:ckfinder_url+'ckfinder.html'
				,filebrowserImageBrowseUrl:ckfinder_url+'ckfinder.html?type=images'
				,filebrowserFlashBrowseUrl:ckfinder_url+'ckfinder.html?type=flash'
				,filebrowserUploadUrl:ckfinder_url+'core/connector/php/connector.php?command=QuickUpload&type=files'
				,filebrowserImageUploadUrl:ckfinder_url+'core/connector/php/connector.php?command=QuickUpload&type=images'
				,filebrowserFlashUploadUrl:ckfinder_url+'core/connector/php/connector.php?command=QuickUpload&type=flash'
				});					
			})
		</script>
		<form method='post'>
			<textarea name='page_content' id='editor'><?php echo $page_content?></textarea>
			<div style='text-align:right;padding:4px'>
				<input type='submit' value='Save' name='submit_value'/>
				<input type='submit' value='Reset to default' name='submit_value'/>
				<input type='button' value='Close' onclick="window.location='?page=<?php echo Page::$_page_name?>'"/>
			</div>
		</form>
	<?php
	}
	
	static private $_page_name;
	static public function init($page_name)
	{
		global $action;
		Page::$_page_name=$page_name;
		switch($action)
		{
			case '':
				Page::view();
				break;
			case 'edit':
				Page::edit();
				break;
		}
	}
}

class Common
{	
	static function header_location($url,$message=null,$script_afer_alert="")
	{
		if($url==null)
			$url_script='';
		else if(is_numeric($url))
			$url_script="history.go($url);";
		else
			$url_script="window.location='$url';" ;
		$message_script=$message==null?'':"alert('$message');";		
		if($url==null)
		{
			$script="<script>$(document).ready(function(){ $message_script $script_afer_alert});</script>";
			echo ($script);
		}
		else 
		{
			$script="<script> $message_script $url_script </script>";
			die($script);
		}
	}
	
	static function init()
	{	
		//
		global $page;
		global $action;
		global $language;
		global $login;
		global $pages; 
		
		//
		require_once "config.php";
		
		//
		session_start();
		if(!isset($_SESSION['base_url']))
			$_SESSION['base_url']=BASE_URL;
		if(!isset($_SESSION['language']))
			$_SESSION['language']=DEFAULT_LANGUAGE;
		if(!isset($_SESSION['login']))
			$_SESSION['login']=0;
		$login=$_SESSION['login'];
		$language=$_SESSION['language'];		
		
		//
		require_once "$language.php";
		
		//
		$page=isset($_GET['page'])?$_GET['page']:DEFAULT_PAGE;
		$pages=array('homepage'=>LHOMEPAGE,'profile'=>LPROFILE,'project'=>LPROJECT,'news'=>LNEWS,'contact'=>LCONTACT);
		$action=isset($_GET['action'])?$_GET['action']:'';
	}
}

Common::init();
?>